﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Windows.Forms;
using System.Data;

namespace OrBitDataModule.Common
{
    public static class FileSizeFormatter
    {
        private const long BYTE = 1;
        private const long KB = BYTE * 1024;
        private const long MB = KB * 1024;
        private const long GB = MB * 1024;
        private const long TB = GB * 1024;


        public static string FormatSize(long bytes)
        {
            double size = bytes;

            if (size < KB)
                return string.Format("{0} B", bytes); // 字节
            if (size < MB)
                return string.Format("{0:F2} KB", size / KB); // 千字节
            if (size < GB)
                return string.Format("{0:F2} MB", size / MB); // 兆字节
            if (size < TB)
                return string.Format("{0:F2} GB", size / GB); // 吉字节

            return string.Format("{0:F2} TB", size / TB); // 太字节
        }
    }
    public class Tools
    {
        /// <summary>
        /// 转换Image为Icon
        /// </summary>
        /// <param name="image">要转换为图标的Image对象</param>
        /// <param name="nullTonull">当image为null时是否返回null。false则抛空引用异常</param>
        /// <exception cref="ArgumentNullException" />
        public static Icon ConvertToIcon(Image image, bool nullTonull = false)
        {
            if (image == null)
            {
                if (nullTonull) { return null; }
            }
            using (MemoryStream msImg = new MemoryStream(), msIco = new MemoryStream())
            {
                image.Save(msImg, ImageFormat.Png);
                using (var bin = new BinaryWriter(msIco))
                {
                    bin.Write((short)0);
                    bin.Write((short)1);
                    bin.Write((short)1);

                    bin.Write((byte)image.Width);
                    bin.Write((byte)image.Height);
                    bin.Write((byte)0);
                    bin.Write((byte)0);
                    bin.Write((short)0);
                    bin.Write((short)32);
                    bin.Write((int)msImg.Length);
                    bin.Write(22);

                    bin.Write(msImg.ToArray());

                    bin.Flush();
                    bin.Seek(0, SeekOrigin.Begin);
                    return new Icon(msIco);
                }
            }
        }
    }
}